#include "markeritem.h"

#include <QPainter>
#include <QGraphicsScene>
#include <QGraphicsDropShadowEffect>
#include <qmath.h>

#include <QDebug>

const qreal MarkerWidth = 20;
const qreal MarkerHeight = qSqrt(qPow(MarkerWidth, 2) - qPow((MarkerWidth / 2), 2));

MarkerItem::MarkerItem(QGraphicsItem* parent)
    : QGraphicsObject(parent), m_yPos(0)
{
    setFlag(QGraphicsItem::ItemIsFocusable);
    setFlag(QGraphicsItem::ItemIsSelectable);
    setFlag(QGraphicsItem::ItemIsMovable);
    setFlag(QGraphicsItem::ItemSendsGeometryChanges);
}

void MarkerItem::setYPos(qreal yPos)
{
    m_yPos = yPos;
}

QRectF MarkerItem::boundingRect() const
{
    return QRectF(-MarkerWidth / 2, -MarkerHeight / 2, MarkerWidth, MarkerHeight);
}

void MarkerItem::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
{
    painter->setRenderHint(QPainter::Antialiasing);
    painter->setBrush(QBrush(isSelected() ? Qt::yellow : Qt::gray));

    QPainterPath markerPath(QPointF(-MarkerWidth / 2, -MarkerHeight / 2));
    markerPath.lineTo(QPointF(MarkerWidth / 2, -MarkerHeight / 2));
    markerPath.lineTo(QPointF(0, MarkerHeight / 2));
    markerPath.closeSubpath();

    painter->drawPath(markerPath);
}

QVariant MarkerItem::itemChange(GraphicsItemChange change, const QVariant& value)
{
    if (change == ItemPositionChange && scene())
    {
        QPointF newPos = value.toPointF();
        newPos.setY(m_yPos);

        QRectF rect = scene()->sceneRect();
        if (!rect.contains(newPos)) {
            newPos.setX(qMin(rect.right(), qMax(newPos.x(), rect.left())));
            newPos.setY(qMin(rect.bottom(), qMax(newPos.y(), rect.top())));
            return newPos;
        }

        return newPos;
    }
    return QGraphicsItem::itemChange(change, value);
}

void MarkerItem::focusInEvent(QFocusEvent* event)
{
    QGraphicsDropShadowEffect* effect = new QGraphicsDropShadowEffect(this);
    effect->setBlurRadius(10);
    effect->setOffset(0, -7);
    effect->setColor(Qt::white);
    setGraphicsEffect(effect);
    setZValue(1);
    emit focusChanged();
}

void MarkerItem::focusOutEvent(QFocusEvent* event)
{
    setGraphicsEffect(NULL);
    setZValue(0);
    emit focusChanged();
}
